package com.yxh.bigdata.zookeeper.zk;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

/**
 * 监听服务器上下线服务端
 * @author: 印修河
 * @date: 2018/5/1 9:43
 */
public class DistributedServer {

    private static final String CONNECT_HOST = "localhost:2181";
    private static final int SESSION_TIMEOUT = 2000;

    public static void main(String[] args) throws Exception {
        //获取zookeeper连接
        ZooKeeper zkClient = getConnect();
        //创建临时节点
        zkClient.create("/servers/server", args[0].getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);
        //业务代码
        Thread.sleep(Long.MAX_VALUE);
    }

    private static ZooKeeper getConnect() throws Exception {
        ZooKeeper zkClient = new ZooKeeper(CONNECT_HOST, SESSION_TIMEOUT, event -> {
            //收到事件通知后的通知函数
            System.out.println(event.getType() + "====" + event.getPath());
        });
        return zkClient;
    }
}
